<template>
  <el-select
    v-bind="$attrs"
    @input="handleInput"
    filterable
    :remote="true"
    :remote-method="remoteSearch"
    clearable
    @change="handleChange"
    @clear="handleClear"
  >
    <el-option
      v-for="item in consigneeOptions"
      :key="item.value"
      :label="item.label"
      :value="item.value"
    >
      <span style="float: left">{{ item.label }}</span>
      <span style="float: right; color: #8492a6; font-size: 13px">{{
        item.customerName
      }}</span>
    </el-option>
  </el-select>
</template>

<script>
import { mapActions, mapState } from "vuex";
export default {
  name: "SimpleConsigneeSelect",
  data() {
    return {
      loading: false,
      selectedValue: null
    };
  },
  computed: {
    ...mapState({
      consigneeList: (state) => state.consignee.consigneeList
    }),
    consigneeOptions() {
      return this.consigneeList.map((consignee) => {
        return {
          ...consignee,
          label: consignee.consigneeName,
          value: consignee.consigneeId
        };
      });
    },
    filteredConsignee() {
      if (!this.selectedValue || this.selectedValue.length === 0) {
        return [];
      }
      let consigneeIds = [];
      if (typeof this.selectedValue === Array) {
        consigneeIds = [...this.selectedValue];
      } else {
        consigneeIds = [this.selectedValue];
      }

      return this.consigneeList.filter((consignee) =>
        consigneeIds.includes(consignee.consigneeId)
      );
    }
  },
  created() {
    this.search();
  },
  methods: {
    ...mapActions({
      search: "consignee/search"
    }),
    handleInput(value) {
      this.selectedValue = value;
      this.$emit("input", value);
    },
    async remoteSearch(query) {
      if (query !== "") {
        this.loading = true;
        await this.search({ consigneeName: query });
        this.loading = false;
      }
    },
    handleClear() {
      this.search({});
    },
    handleChange() {
      if (this.filteredConsignee.length === 1) {
        this.$emit("confirm", this.filteredConsignee[0]);
      } else if (this.filteredConsignee.length > 1) {
        this.$emit("confirm", this.filteredConsignee);
      }
    }
  }
};
</script>
